import React, { PureComponent } from 'react'
import { connect } from 'dva'
import {
  Button,
  Input,
  Spin,
  Form,
  Row,
  Col,
  Card,
  Select,
  Radio,
  Checkbox,
  message
} from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { LZFormItem } from '@/components/LZForm'
import formRules from '@/utils/formRules'
import { goToRouter } from '@/utils/utils'
import { cloneDeep, isEqual } from 'lodash'
import { router } from 'umi'
import Services from './services/index'
import RouterWillLeave from '@/components/RouterWillLeave'

const FormItem = Form.Item
const { Option } = Select

const typeMap = {
  BUY_OUT: '买断',
  RENT_MONTH: '月租金分账',
  RENT_THREE: '三月所有租金分账',
  RENT_ALL: '首月所有租金分账'
}

const formItemLayout = {
  labelCol: {
    span: 3
  },
  wrapperCol: {
    span: 16
  }
}

const subFormItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
}
const subFormItemLayoutAliPay = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 16
  }
}

@connect()
@Form.create()
class AddCommission extends PureComponent {
  state = {
    id: '',
    loading: false,
    checkShop: false,
    checkBuyout: false,
    checkRent: false,
    rentType: 'RENT_THREE',
    help: '',
    commissionDetail: {},
    shopList: [],
    shopInfo: {},
    validateStatus: '',
    rules: [],
    originData: {},
    isSubmit: false
  }

  componentWillMount() {
    const {
      match: {
        params: { id }
      }
    } = this.props
    this.getShopList()
    if (id) {
      this.setState({
        loading: true,
        id
      })
      Services.detail({ id })
        .then(res => {
          const check = {}
          const _rules = res.rules.map(v => {
            v.platformRate = 100 - v.scale * 100
            const { type } = v
            if (type === 'BUY_OUT') {
              check.checkBuyout = true
            } else if (type === 'SHOPPING') {
              check.checkShop = true
            } else {
              check.checkRent = true
            }
            return v
          })
          const item = _rules.find(f => f.type.includes('RENT'))
          let rentType = 'RENT_THREE'
          if (item) {
            rentType = item.type
          }
          this.setState({
            commissionDetail: res.account || {},
            rules: _rules.map(rule => {
              return {
                ...rule,
                scale: Number(rule.scale) * 100
              }
            }),
            shopInfo: res.account || {},
            rentType,
            ...check
          })
          this.handleOriginData()
        })
        .finally(() => {
          this.setState({
            loading: false
          })
        })
    }
  }

  componentDidMount() {
    this.handleOriginData()
  }

  getShopList = () => {
    Services.getShopList().then(res => {
      this.setState({
        shopList: res || []
      })
    })
  }

  handleOriginData = () => {
    const values = this.props.form.getFieldsValue()
    this.setState({
      originData: values
    })
  }

  checkSum = field => {
    return {
      validator: (rule, value, callback) => {
        return new Promise((resolve, reject) => {
          const total =
            Number(this.props.form.getFieldValue(field)) + Number(value)
          if (value > 100) {
            reject('分佣比例不能超过100!')
          } else if (parseInt(total) > 100) {
            reject('分佣比例之和超过100!')
          } else {
            resolve()
          }
        })
      }
    }
  }

  rules = {
    shopName: [formRules.required('请选择店铺名称')],
    type: [formRules.required('请选择分佣类型')],
    delayNum: [formRules.required('请输入自然日')],
    name: [formRules.required('请输入姓名')],
    identity: [formRules.required('请输入支付宝账号')],
    scale: [
      formRules.required('请输入商家占比'),
      formRules.float,
      this.checkSum('platformRate')
    ],
    platformRate: [
      formRules.required('请输入平台占比'),
      formRules.float,
      this.checkSum('scale')
    ]
  }

  handleSubmit = e => {
    const { form, dispatch } = this.props
    const {
      checkBuyout,
      checkShop,
      checkRent,
      rules,
      shopInfo,
      id
    } = this.state
    e.preventDefault()
    form.validateFields((err, fieldsValue) => {
      if (err) return
      if (checkShop || checkBuyout || checkRent) {
        this.setState({
          isSubmit: true
        })

        let myRules = JSON.parse(JSON.stringify(rules))

        if (!checkShop) {
          myRules = rules.filter(item => item.type !== 'SHOPPING')
        }
        if (!checkBuyout) {
          myRules = rules.filter(item => item.type !== 'BUY_OUT')
        }
        if (!checkRent) {
          myRules = rules.filter(item => item.type !== 'RENT_MONTH')
        }

        const _rules = myRules.map(rule => {
          return {
            ...rule,
            accountId: id,
            scale: (Number(rule.scale) / 100).toFixed(2),
            delayType: 'NATUREDAY'
          }
        })
        const service = id ? Services.update : Services.add
        // debugger
        service({
          account: {
            ...shopInfo,
            ...fieldsValue,
            id
          },
          rules: _rules
        }).then(res => {
          message.success('提交成功')
          this.handleCancel()
        })
      } else {
        this.setState({
          help: '请至少选择一个分佣类型',
          validateStatus: 'error'
        })
      }
    })
  }

  handleCancel = () => {
    router.push('/commission/list')
  }

  checkType = () => {
    const { checkBuyout, checkShop, checkRent } = this.state
    if (checkBuyout || checkShop || checkRent) {
      this.setState({
        help: ''
      })
    } else {
      this.setState({
        help: '请至少选择一个分佣类型',
        validateStatus: 'error'
      })
    }
  }

  handleCheckShopChange = evt => {
    const { rules } = this.state
    debugger
    const item = rules.find(f => f.type === 'SHOPPING')
    if (!item) {
      rules.push({ type: 'SHOPPING' })
    }
    this.setState({
      checkShop: evt.target.checked,
      rules
    })
  }

  handleCheckBuyoutChange = evt => {
    const { rules } = this.state
    const item = rules.find(f => f.type === 'BUY_OUT')
    if (!item) {
      rules.push({ type: 'BUY_OUT' })
    }
    this.setState({
      checkBuyout: evt.target.checked
    })
  }

  handleCheckRentChange = evt => {
    const { rules } = this.state
    const item = rules.find(f => f.type.includes('RENT'))
    if (!item) {
      rules.push({ type: 'RENT_THREE' })
    }
    this.setState({
      checkRent: evt.target.checked,
      rentType: 'RENT_THREE'
    })
  }

  handleShopChange = value => {
    const item = this.state.shopList.find(f => f.shopName === value)
    this.setState({
      shopInfo: item,
      validateStatus: '',
      help: ''
    })
  }

  handleRent = value => {
    const { rules } = this.state
    const _rules = [...rules]
    const _detailIndex = _rules.findIndex(f => f.type.includes('RENT'))
    _rules[_detailIndex].type = value
    this.setState({
      rentType: value,
      rules: _rules
    })
  }

  handleValueChange = (evt, field, type) => {
    const { rules } = this.state
    const _detailIndex = rules.findIndex(f => f.type === type)
    console.log(type, _detailIndex)
    const _rules = cloneDeep(rules)
    _rules[_detailIndex][field] = evt.target.value
    this.setState({
      rules: _rules
    })
  }

  renderMonth = (getFieldDecorator, field, checkStatus) => {
    if (!this.state[checkStatus]) {
      return null
    }
    const { rules } = this.state
    const detailIndex = rules.findIndex(f => f.type === field)
    console.log(detailIndex)
    const detail = rules[detailIndex] || {}

    return (
      <div className="commission-sub-form">
        <LZFormItem
          label="结算周期"
          field="delayNum"
          getFieldDecorator={getFieldDecorator}
          // rules={this.rules.delayNum}
          required={false}
          formItemLayout={subFormItemLayout}
          initialValue={detail.delayNum}
        >
          <Radio checked>
            按
            <Input
              className="nature-day-input"
              value={detail.delayNum}
              onChange={evt => this.handleValueChange(evt, 'delayNum', field)}
            />
            个自然日
          </Radio>
        </LZFormItem>
        <FormItem
          label="分佣比例"
          {...subFormItemLayout}
          className="commission-rate"
        >
          <Row>
            <FormItem {...subFormItemLayoutAliPay} label="商家占比">
              <Input
                value={detail.scale}
                onChange={evt => this.handleValueChange(evt, 'scale', field)}
              />
            </FormItem>
          </Row>
          <Row>
            <FormItem {...subFormItemLayoutAliPay} label="平台占比">
              <Input
                value={detail.platformRate}
                onChange={evt =>
                  this.handleValueChange(evt, 'platformRate', field)
                }
              />
            </FormItem>
          </Row>
        </FormItem>
      </div>
    )
  }

  renderRouterWillLeave = () => {
    const { originData, isSubmit } = this.state
    const values = this.props.form.getFieldsValue()
    const isPrompt = !isEqual(values, originData)
    return <RouterWillLeave isPrompt={isPrompt} isSubmit={isSubmit} />
  }

  render() {
    const {
      form: { getFieldDecorator }
    } = this.props
    const {
      loading,
      commissionDetail,
      shopList,
      shopInfo,
      rentType,
      checkRent,
      validateStatus,
      help,
      checkShop,
      checkBuyout,
      id
    } = this.state
    const title = id ? '修改佣金' : '新增佣金'

    return (
      <PageHeaderWrapper title={title}>
        {this.renderRouterWillLeave()}
        <Card>
          <Spin spinning={loading}>
            <Form {...formItemLayout} colon>
              <LZFormItem
                label="店铺名称"
                field="shopName"
                rules={this.rules.shopName}
                getFieldDecorator={getFieldDecorator}
                initialValue={commissionDetail.shopName}
              >
                <Select
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.props.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  showSearch
                  placeholder="请选择店铺名称"
                  onChange={this.handleShopChange}
                >
                  {shopList.map(shop => {
                    return (
                      <Option value={shop.shopName} key={shop.shopName}>
                        {shop.shopName}
                      </Option>
                    )
                  })}
                </Select>
              </LZFormItem>
              <LZFormItem
                getFieldDecorator={getFieldDecorator}
                label="企业资质名称"
                field="shopFirmInfo"
                initialValue={shopInfo.shopFirmInfo}
              >
                <Input placeholder="请输入企业资质名称" disabled />
              </LZFormItem>
              <LZFormItem
                label="店铺编号"
                field="shopId"
                getFieldDecorator={getFieldDecorator}
                initialValue={shopInfo.shopId}
              >
                <Input placeholder="请输入店铺编号" disabled />
              </LZFormItem>
              <LZFormItem
                label="分佣类型"
                field="type"
                getFieldDecorator={getFieldDecorator}
                className="fenyong-type"
                validateStatus={validateStatus}
                help={help}
              >
                <Checkbox
                  checked={checkRent}
                  className="rent-checkbox"
                  onChange={this.handleCheckRentChange}
                >
                  <Select
                    value={rentType}
                    onChange={this.handleRent}
                    disabled={!checkRent}
                    className="w-214"
                  >
                    <Select.Option value="RENT_MONTH">月租金</Select.Option>
                    <Select.Option value="RENT_ALL">全期租金</Select.Option>
                    <Select.Option value="RENT_THREE">
                      第三期时扣取剩余平台租金
                    </Select.Option>
                  </Select>
                </Checkbox>
              </LZFormItem>
              {this.renderMonth(getFieldDecorator, rentType, 'checkRent')}
              <div className="commission-sub-footer">
                <Checkbox
                  checked={checkBuyout}
                  onChange={this.handleCheckBuyoutChange}
                >
                  买断尾款
                </Checkbox>
              </div>
              {this.renderMonth(getFieldDecorator, 'BUY_OUT', 'checkBuyout')}
              <div className="commission-sub-footer">
                <Checkbox
                  checked={checkShop}
                  onChange={this.handleCheckShopChange}
                >
                  购买佣金
                </Checkbox>
              </div>
              {this.renderMonth(getFieldDecorator, 'SHOPPING', 'checkShop')}
              <FormItem
                label="商家支付宝信息"
                className="aliPay-info"
                field="name"
                getFieldDecorator={getFieldDecorator}
                rules={this.rules.name}
                formItemLayout={subFormItemLayoutAliPay}
                required={false}
                initialValue={commissionDetail.name}
              >
                <Row>
                  <Col span={3}>
                    <LZFormItem
                      field="name"
                      getFieldDecorator={getFieldDecorator}
                      rules={this.rules.name}
                      required={false}
                      initialValue={commissionDetail.name}
                    >
                      <Input
                        style={{ width: '112px' }}
                        placeholder="请输入姓名"
                      />
                    </LZFormItem>
                  </Col>
                  <Col span={12} offset={1}>
                    <LZFormItem
                      field="identity"
                      getFieldDecorator={getFieldDecorator}
                      rules={this.rules.identity}
                      initialValue={commissionDetail.identity}
                    >
                      <Input
                        style={{ width: '187px' }}
                        placeholder="请输入支付宝账号"
                      />
                    </LZFormItem>
                  </Col>
                </Row>
              </FormItem>

              <FormItem>
                <div className="footer-btns ml-135">
                  <Button onClick={this.handleCancel}>取消</Button>
                  <Button
                    type="primary"
                    htmlType="submit"
                    onClick={this.handleSubmit}
                  >
                    确定
                  </Button>
                </div>
              </FormItem>
            </Form>
          </Spin>
        </Card>
      </PageHeaderWrapper>
    )
  }
}
export default AddCommission
